package com.zenithmind.library.pojo.domain;

import com.baomidou.mybatisplus.annotation.TableName;
import com.zenithmind.common.base.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 图书库存管理实体
 * 遵循单一职责原则：只负责图书库存相关的管理
 * 
 * @author ZenithMind
 * @since 2024-06-14
 */
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(name = "图书库存实体", description = "图书库存管理信息")
@TableName("lib_book_inventory")
public class BookInventory extends BaseEntity {

    @NotNull(message = "图书ID不能为空")
    @Schema(description = "图书ID")
    private String bookId;

    @Schema(description = "总库存数量")
    private Integer totalCopies;

    @Schema(description = "可借阅数量")
    private Integer availableCopies;

    @Schema(description = "已借出数量")
    private Integer borrowedCopies;

    @Schema(description = "预约数量")
    private Integer reservedCopies;

    @Schema(description = "维护中数量")
    private Integer maintenanceCopies;

    @Schema(description = "损坏数量")
    private Integer damagedCopies;

    @Schema(description = "丢失数量")
    private Integer lostCopies;

    /**
     * 检查是否有可借阅的副本
     */
    public boolean hasAvailableCopies() {
        return availableCopies != null && availableCopies > 0;
    }

    /**
     * 检查库存是否充足
     */
    public boolean isStockSufficient(int requestedQuantity) {
        return hasAvailableCopies() && availableCopies >= requestedQuantity;
    }

    /**
     * 借出图书（减少可借阅数量，增加已借出数量）
     */
    public boolean borrowCopy() {
        if (!hasAvailableCopies()) {
            return false;
        }
        availableCopies--;
        borrowedCopies = (borrowedCopies == null ? 0 : borrowedCopies) + 1;
        return true;
    }

    /**
     * 归还图书（增加可借阅数量，减少已借出数量）
     */
    public boolean returnCopy() {
        if (borrowedCopies == null || borrowedCopies <= 0) {
            return false;
        }
        borrowedCopies--;
        availableCopies = (availableCopies == null ? 0 : availableCopies) + 1;
        return true;
    }

    /**
     * 预约图书（减少可借阅数量，增加预约数量）
     */
    public boolean reserveCopy() {
        if (!hasAvailableCopies()) {
            return false;
        }
        availableCopies--;
        reservedCopies = (reservedCopies == null ? 0 : reservedCopies) + 1;
        return true;
    }

    /**
     * 取消预约（增加可借阅数量，减少预约数量）
     */
    public boolean cancelReservation() {
        if (reservedCopies == null || reservedCopies <= 0) {
            return false;
        }
        reservedCopies--;
        availableCopies = (availableCopies == null ? 0 : availableCopies) + 1;
        return true;
    }

    /**
     * 标记为损坏（从相应状态转移到损坏状态）
     */
    public boolean markAsDamaged(String fromStatus) {
        switch (fromStatus.toLowerCase()) {
            case "available":
                if (availableCopies == null || availableCopies <= 0) return false;
                availableCopies--;
                break;
            case "borrowed":
                if (borrowedCopies == null || borrowedCopies <= 0) return false;
                borrowedCopies--;
                break;
            case "reserved":
                if (reservedCopies == null || reservedCopies <= 0) return false;
                reservedCopies--;
                break;
            case "maintenance":
                if (maintenanceCopies == null || maintenanceCopies <= 0) return false;
                maintenanceCopies--;
                break;
            default:
                return false;
        }
        damagedCopies = (damagedCopies == null ? 0 : damagedCopies) + 1;
        return true;
    }

    /**
     * 标记为丢失（从相应状态转移到丢失状态）
     */
    public boolean markAsLost(String fromStatus) {
        switch (fromStatus.toLowerCase()) {
            case "available":
                if (availableCopies == null || availableCopies <= 0) return false;
                availableCopies--;
                break;
            case "borrowed":
                if (borrowedCopies == null || borrowedCopies <= 0) return false;
                borrowedCopies--;
                break;
            case "reserved":
                if (reservedCopies == null || reservedCopies <= 0) return false;
                reservedCopies--;
                break;
            case "maintenance":
                if (maintenanceCopies == null || maintenanceCopies <= 0) return false;
                maintenanceCopies--;
                break;
            default:
                return false;
        }
        lostCopies = (lostCopies == null ? 0 : lostCopies) + 1;
        return true;
    }

    /**
     * 计算库存利用率
     */
    public BigDecimal getUtilizationRate() {
        if (totalCopies == null || totalCopies == 0) {
            return BigDecimal.ZERO;
        }
        int usedCopies = (borrowedCopies == null ? 0 : borrowedCopies) + 
                        (reservedCopies == null ? 0 : reservedCopies);
        return BigDecimal.valueOf(usedCopies)
                .divide(BigDecimal.valueOf(totalCopies), 4, RoundingMode.HALF_UP);
    }

    /**
     * 验证库存数据一致性
     */
    public boolean validateInventory() {
        int calculatedTotal = (availableCopies == null ? 0 : availableCopies) +
                             (borrowedCopies == null ? 0 : borrowedCopies) +
                             (reservedCopies == null ? 0 : reservedCopies) +
                             (maintenanceCopies == null ? 0 : maintenanceCopies) +
                             (damagedCopies == null ? 0 : damagedCopies) +
                             (lostCopies == null ? 0 : lostCopies);
        
        return totalCopies != null && totalCopies.equals(calculatedTotal);
    }
}
